# demo_socket_server_2.py文件
import logging
import socket

logging.basicConfig(level=logging.DEBUG,
                    format="%(asctime)s>%(message)s", datefmt="%Y-%m-%d %H:%M:%S")
logger = logging.getLogger(__name__)

import threading
import time

class ServerClass(object):
    """docstring for ServerClass"""

    def __init__(self):
        self.__HOST = "192.168.211.182"
        self.__PORT = 8088
        self.ADDR = (self.__HOST, self.__PORT)
        self.__TCP_SOCKET = socket.socket(
            family=socket.AF_INET, type=socket.SOCK_STREAM)
        # 设置非阻塞
        # self.__TCP_SOCKET.setblocking(False)
        self.__TCP_SOCKET.settimeout(0.0)
        # 用来存放套接字对象的列表
        self.connlist = list()
        self.__TCP_SOCKET.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.conn_dict = dict()

    def start_server(self, lightPlayer):
        with self.__TCP_SOCKET as sock:
            sock.bind(self.ADDR)
            sock.listen()
            logger.info("Server is Running")
            while True:
                try:
                    conn, addr = sock.accept()
                    print(conn)
                    print(conn.fileno())
                    # logger.info(conn)
                    # 将连接的套接字对象设置为非阻塞
                    conn.setblocking(False)
                    print('11111')
                    # msg = f"Hi,{addr}"
                    # self.send_data(conn, msg)
                    # 添加到列表
                    self.connlist.append(conn)
                    print('000000')
                # 如果没有连接进来需要捕获BlockingIOError异常
                except BlockingIOError as e:
                    pass
                    # logger.debug("没有新的客户端连接")
                # 循环套接字对象列表 进行收发数据
                for conn in self.connlist:
                    # print(conn)
                    msg = self.recv_data(conn)
                    if msg:
                        send_t = threading.Thread(target=self.send_data, args=(conn, msg, lightPlayer))
                        send_t.stop_event = threading.Event()
                        send_t.start()
                        print(send_t)
                        self.conn_dict[conn.fileno()] = send_t

    def recv_data(self, conn):
        """接收数据"""
        try:
            msg = conn.recv(1024).decode("utf-8")
            print('recv msg---------', msg)
            if msg == 'start':
                print('****************8')
                return True
            elif msg in ["quit"]:
                logger.debug("断开连接")
                # 将套接字对象从列表移除
                self.connlist.remove(conn)
                self.conn_dict[conn.fileno()].stop_event.set()
            else:
                logger.info(msg)
                return msg
        except IOError as e:
            pass
            # logger.debug("没有接收到数据")

    def send_data(self, conn, msg, lightPlayer):
        """发送数据"""
        if msg:
            msg = f"From Server {msg}"
            try:
                while True:
                    if threading.current_thread().stop_event.wait(0):
                        break
                    else:
                        audioData = lightPlayer.getAudioStream()
                        num_bytes = audioData.to_bytes(1, byteorder='big')
                        conn.sendall(num_bytes)
                        time.sleep(1)
            except ConnectionResetError as e:
                pass
                logger.debug("连接已断开，无法再发送信息")


if __name__ == '__main__':
    ServerClass().start_server()
